<template>
  <div class="app-container">
    <!-- 项目信息 -->
    <el-card class="project-info-card" shadow="never">
      <div class="project-header">
        <div class="project-details">
          <h2>{{ project.title }}</h2>
          <p class="project-desc">{{ project.description }}</p>
          <div class="project-meta">
            <span class="meta-item">
              <i class="el-icon-date"></i>
              {{ project.startDate }} ~ {{ project.endDate }}
            </span>
            <el-tag :type="getStatusType(project.status)">
              {{ getStatusText(project.status) }}
            </el-tag>
          </div>
        </div>
        <div class="project-actions">
          <el-button @click="goBack">返回项目</el-button>
          <el-button type="primary" @click="handleAddMilestone">
            添加节点
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 节点列表 -->
    <el-card class="milestone-card">
      <div slot="header" class="card-header">
        <h3>项目节点</h3>
        <span class="milestone-count">共 {{ milestones.length }} 个节点</span>
      </div>

      <div class="milestone-timeline" v-loading="loading">
        <div v-for="milestone in milestones" :key="milestone.id" class="milestone-item" :class="{
          'completed': milestone.status === 2,
          'in-progress': milestone.status === 1,
          'not-started': milestone.status === 0
        }">
          <div class="milestone-marker">
            <i
              :class="milestone.status === 2 ? 'el-icon-check' : (milestone.status === 1 ? 'el-icon-time' : 'el-icon-circle-plus')"></i>
          </div>

          <div class="milestone-content">
            <div class="milestone-header">
              <h4 class="milestone-title">{{ milestone.title }}</h4>
              <div class="milestone-actions">
                <el-tag :type="getStatusType(milestone.status)" size="small">
                  {{ getStatusText(milestone.status) }}
                </el-tag>
                <el-button size="mini" @click="handleEditMilestone(milestone)">
                  编辑
                </el-button>
                <el-button size="mini" type="danger" @click="handleDeleteMilestone(milestone)">
                  删除
                </el-button>
              </div>
            </div>

            <p class="milestone-desc">{{ milestone.description }}</p>

            <div class="milestone-info">
              <div class="info-item" v-if="milestone.startDate">
                <i class="el-icon-date"></i>
                <span>开始日期：{{ milestone.startDate | parseTime('{y}-{m}-{d}') }}</span>
              </div>
              <div class="info-item" v-if="milestone.endDate">
                <i class="el-icon-date"></i>
                <span>结束日期：{{ milestone.endDate | parseTime('{y}-{m}-{d}') }}</span>
              </div>
              <div class="info-item">
                <i class="el-icon-alarm-clock"></i>
                <span>截止日期：{{ milestone.deadline | parseTime('{y}-{m}-{d}') }}</span>
              </div>
              <div class="info-item">
                <i class="el-icon-bell"></i>
                <span>提前 {{ milestone.reminderDays }} 天提醒</span>
              </div>
            </div>

            <!-- 文档列表 -->
            <div class="milestone-documents" v-if="getDocuments(milestone).length > 0">
              <h5>已提交文档：</h5>
              <div class="document-list">
                <div v-for="doc in getDocuments(milestone)" :key="doc.name" class="document-item">
                  <i class="el-icon-document"></i>
                  <span class="doc-name">{{ doc.name }}</span>
                  <span class="doc-uploader">{{ doc.uploader }}</span>
                  <span class="doc-time">{{ doc.uploadTime }}</span>
                  <el-button type="text" size="mini" @click="downloadDocument(doc)">
                    下载
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && milestones.length === 0" class="empty-state">
        <div class="empty-content">
          <i class="el-icon-time" style="font-size: 48px; color: #C0C4CC;"></i>
          <p style="color: #909399; margin: 16px 0;">暂无项目节点</p>
          <el-button type="primary" @click="handleAddMilestone">
            添加第一个节点
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑节点对话框 -->
    <el-dialog :title="dialogMode === 'add' ? '添加节点' : '编辑节点'" :visible.sync="dialogVisible" width="600px"
      :modal-append-to-body="true" :append-to-body="true" :z-index="2000" @opened="handleDialogOpened"
      @closed="handleDialogClosed" custom-class="milestone-dialog">
      <el-form ref="milestoneForm" :model="milestoneForm" :rules="milestoneRules" label-width="100px">
        <el-form-item label="节点标题" prop="title">
          <el-input v-model="milestoneForm.title" placeholder="请输入节点标题" />
        </el-form-item>

        <el-form-item label="节点描述" prop="description">
          <el-input v-model="milestoneForm.description" type="textarea" :rows="3" placeholder="请描述该节点的具体要求和目标" />
        </el-form-item>

        <div class="form-row">
          <el-form-item label="开始日期" prop="startDate" class="date-item">
            <el-date-picker v-model="milestoneForm.startDate" type="date" placeholder="选择开始日期" style="width: 100%"
              value-format="yyyy-MM-dd" :popper-append-to-body="true" />
          </el-form-item>

          <el-form-item label="结束日期" prop="endDate" class="date-item">
            <el-date-picker v-model="milestoneForm.endDate" type="date" placeholder="选择结束日期" style="width: 100%"
              value-format="yyyy-MM-dd" :popper-append-to-body="true" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="截止日期" prop="deadline" class="deadline-item">
            <el-date-picker v-model="milestoneForm.deadline" type="date" placeholder="选择截止日期" style="width: 100%"
              value-format="yyyy-MM-dd" :popper-append-to-body="true" />
          </el-form-item>

          <el-form-item label="提醒设置" prop="reminderDays" class="reminder-item">
            <el-select v-model="milestoneForm.reminderDays" placeholder="选择提醒时间" :popper-append-to-body="true">
              <el-option label="提前1天" :value="1" />
              <el-option label="提前3天" :value="3" />
              <el-option label="提前5天" :value="5" />
              <el-option label="提前7天" :value="7" />
              <el-option label="提前14天" :value="14" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveMilestone" :loading="saving">
          {{ dialogMode === 'add' ? '添加' : '更新' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import './styles.css'
import { addMilestone, updateMilestone, getProjectDetail, getProjectMilestonesAndDocuments, deleteMilestone } from '@/api/research'

export default {
  name: 'ProjectMilestones',
  filters: {
    parseTime
  },
  mounted() {
    // 修复Element UI弹出层层级问题
    this.fixElementUIPopperZIndex()
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    document.removeEventListener('click', this.checkAndFixPoppers)
  },
  data() {
    return {
      loading: false,
      saving: false,
      projectId: null,
      project: {},
      milestones: [],

      // 对话框相关
      dialogVisible: false,
      dialogMode: 'add', // add 或 edit
      milestoneForm: {
        id: null,
        title: '',
        description: '',
        deadline: '',
        reminderDays: 3
      },
      milestoneRules: {
        title: [
          { required: true, message: '请输入节点标题', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入节点描述', trigger: 'blur' }
        ],
        deadline: [
          { required: true, message: '请选择截止时间', trigger: 'change' }
        ],
        reminderDays: [
          { required: true, message: '请选择提醒时间', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.projectId = this.$route.params.id
    this.loadProjectInfo()
    this.loadMilestones()
  },
  methods: {
    // 加载项目信息
    loadProjectInfo() {
      getProjectDetail(this.projectId).then(response => {
        this.project = response.data
      }).catch((error) => {
        console.error('获取项目详情失败:', error)
        this.$message.error('获取项目详情失败')
      })
    },

    // 加载节点列表
    async loadMilestones() {
      this.loading = true
      try {
        let res = await getProjectMilestonesAndDocuments(this.projectId);
        this.milestones = res.data || [];
      } catch (error) {
        console.error('获取项目节点列表和文档失败:', error);
      } finally {
        this.loading = false
      }
    },
    // 添加节点
    handleAddMilestone() {
      this.dialogMode = 'add'
      this.milestoneForm = {
        id: null,
        title: '',
        description: '',
        deadline: '',
        reminderDays: 3,
        startDate: '',
        endDate: ''
      }
      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs.milestoneForm.clearValidate()
        // 确保弹出层层级正确
        this.fixElementUIPopperZIndex()
      })
    },

    // 编辑节点
    handleEditMilestone(milestone) {
      this.dialogMode = 'edit'
      this.milestoneForm = {
        id: milestone.id,
        title: milestone.title,
        description: milestone.description,
        deadline: milestone.deadline,
        reminderDays: milestone.reminderDays,
        startDate: milestone.startDate || '',
        endDate: milestone.endDate || ''
      }
      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs.milestoneForm.clearValidate()
        // 确保弹出层层级正确
        this.fixElementUIPopperZIndex()
      })
    },

    // 保存节点
    async handleSaveMilestone() {
      this.$refs.milestoneForm.validate(async (valid) => {
        if (valid) {
          this.saving = true

          // 构建要提交的节点数据
          const milestoneData = {
            projectId: this.projectId,
            title: this.milestoneForm.title,
            description: this.milestoneForm.description,
            deadline: this.milestoneForm.deadline,
            reminderDays: this.milestoneForm.reminderDays,
            startDate: this.milestoneForm.startDate,
            endDate: this.milestoneForm.endDate
          }

          // 打印提交节点的数据
          console.log('=== 保存节点数据 ===')
          console.log('操作模式:', this.dialogMode)
          console.log('项目ID:', this.projectId)
          console.log('要提交的数据:', milestoneData)
          console.log('时间戳:', new Date().toLocaleString())
          console.log('===================')

          try {
            let response
            if (this.dialogMode === 'add') {
              // 添加节点
              response = await addMilestone(milestoneData)
              console.log('添加节点API响应:', response)
              this.$message.success('节点添加成功！')
            } else {
              // 更新节点
              milestoneData.id = this.milestoneForm.id
              response = await updateMilestone(milestoneData)
              console.log('更新节点API响应:', response)
              this.$message.success('节点更新成功！')
            }

            this.saving = false
            this.dialogVisible = false
            this.loadMilestones()
          } catch (error) {
            console.error('保存节点失败:', error)
            this.$message.error('保存节点失败，请重试')
            this.saving = false
          }
        }
      })
    },

    // 删除节点
    async handleDeleteMilestone(milestone) {
      try {
        await this.$confirm('确认删除该节点吗？删除后无法恢复。', '删除确认', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await deleteMilestone(milestone.id)
        this.$message.success('节点删除成功');
        console.log(res);
        this.loadMilestones()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除节点失败:', error)
          this.$message.error('删除节点失败，请重试')
        }
      }
    },

    // 下载文档
    downloadDocument(doc) {
      window.open(doc.url, '_blank')
    },

    // 获取文档列表
    getDocuments(milestone) {
      try {
        return JSON.parse(milestone.documents || '[]')
      } catch (e) {
        return []
      }
    },

    // 工具方法
    getStatusType(status) {
      const types = { 0: 'info', 1: 'primary', 2: 'success' }
      return types[status] || 'info'
    },

    getStatusText(status) {
      const texts = { 0: '未开始', 1: '进行中', 2: '已完成' }
      return texts[status] || '未知'
    },

    // 返回项目详情
    goBack() {
      this.$router.push(`/research/detail/${this.projectId}`)
    },


    // 对话框打开后的处理
    handleDialogOpened() {
      // 对话框打开后立即修复弹出层层级
      this.fixElementUIPopperZIndex()

      // 添加全局点击监听，确保每次点击后都检查弹出层
      document.addEventListener('click', this.checkAndFixPoppers)
    },

    // 对话框关闭后的处理
    handleDialogClosed() {
      // 移除全局点击监听，避免内存泄漏
      document.removeEventListener('click', this.checkAndFixPoppers)
    },

    // 检查并修复所有弹出层
    checkAndFixPoppers() {
      setTimeout(() => {
        // 修复日期选择器弹出层
        document.querySelectorAll('.el-picker-panel').forEach(panel => {
          panel.style.zIndex = '9999'
        })

        // 修复下拉菜单弹出层
        document.querySelectorAll('.el-select-dropdown').forEach(dropdown => {
          dropdown.style.zIndex = '9998'
        })

        // 修复时间选择器弹出层
        document.querySelectorAll('.el-time-panel').forEach(panel => {
          panel.style.zIndex = '9999'
        })
      }, 10)
    },

    // 修复Element UI弹出层层级问题
    fixElementUIPopperZIndex() {
      // 修改日期选择器弹出层的z-index
      const datePicker = document.querySelector('.el-date-picker')
      if (datePicker) {
        datePicker.style.zIndex = '9999'
      }

      // 监听日期选择器的打开事件，确保每次打开都设置正确的z-index
      this.$nextTick(() => {
        // 处理日期选择器
        const datePickerInputs = document.querySelectorAll('.el-date-editor input')
        datePickerInputs.forEach(input => {
          input.addEventListener('click', () => {
            setTimeout(() => {
              // 设置所有日期选择器弹出层的z-index
              const datePickerPoppers = document.querySelectorAll('.el-picker-panel')
              datePickerPoppers.forEach(popper => {
                popper.style.zIndex = '9999'
              })

              // 设置时间选择器弹出层的z-index
              const timePanels = document.querySelectorAll('.el-time-panel')
              timePanels.forEach(panel => {
                panel.style.zIndex = '9999'
              })
            }, 100)
          })
        })

        // 处理下拉菜单
        const selectInputs = document.querySelectorAll('.el-select input')
        selectInputs.forEach(input => {
          input.addEventListener('click', () => {
            setTimeout(() => {
              // 设置所有下拉菜单弹出层的z-index
              const dropdowns = document.querySelectorAll('.el-select-dropdown')
              dropdowns.forEach(dropdown => {
                dropdown.style.zIndex = '9998'

                // 确保下拉菜单内容可见
                const dropdownList = dropdown.querySelector('.el-select-dropdown__wrap')
                if (dropdownList) {
                  dropdownList.style.maxHeight = '274px'
                }
              })
            }, 100)
          })
        })

        // 全局处理所有弹出层
        document.querySelectorAll('.el-popper').forEach(popper => {
          popper.style.zIndex = '9990'
        })
      })
    }
  }
}
</script>

<style scoped>
.project-info-card {
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.project-details h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.project-desc {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.5;
}

.project-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.meta-item i {
  margin-right: 4px;
}

.project-actions {
  display: flex;
  gap: 12px;
}

.milestone-card {
  border: 1px solid #EBEEF5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.milestone-count {
  color: #909399;
  font-size: 14px;
}

.milestone-timeline {
  position: relative;
  padding-left: 30px;
}

.milestone-timeline::before {
  content: '';
  position: absolute;
  left: 15px;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #E4E7ED;
}

.milestone-item {
  position: relative;
  margin-bottom: 30px;
  padding-bottom: 20px;
}

.milestone-item:last-child {
  margin-bottom: 0;
}

.milestone-marker {
  position: absolute;
  left: -22px;
  top: 0;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 2px solid #E4E7ED;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 默认未开始状态 */
  background: #F5F7FA;
  color: #909399;
}

/* 进行中状态样式 */
.milestone-item.in-progress .milestone-marker {
  background: #409EFF;
  border-color: #409EFF;
  color: white;
}

/* 已完成状态样式 */
.milestone-item.completed .milestone-marker {
  background: #67C23A;
  border-color: #67C23A;
  color: white;
}

.milestone-content {
  background: #FAFAFA;
  border: 1px solid #EBEEF5;
  border-radius: 6px;
  padding: 20px;
}

.milestone-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.milestone-title {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.milestone-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.milestone-desc {
  margin: 0 0 16px 0;
  color: #606266;
  line-height: 1.5;
}

.milestone-info {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 13px;
}

.info-item i {
  margin-right: 4px;
}

.milestone-documents {
  border-top: 1px solid #E4E7ED;
  padding-top: 16px;
}

.milestone-documents h5 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.document-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.document-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: white;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  font-size: 13px;
}

.doc-name {
  font-weight: 500;
  color: #303133;
}

.doc-uploader {
  color: #909399;
}

.doc-time {
  color: #C0C4CC;
  margin-left: auto;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-header {
    flex-direction: column;
    gap: 16px;
  }

  .project-actions {
    align-self: stretch;
  }

  .milestone-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .milestone-info {
    flex-direction: column;
    gap: 8px;
  }

  .document-item {
    flex-wrap: wrap;
  }

  /* 表单样式 */
  .form-row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10px;
  }

  .date-item {
    flex: 1;
    min-width: 300px;
    padding: 0 10px;
    margin-bottom: 0;
  }

  .deadline-item {
    flex: 1;
    min-width: 300px;
    padding: 0 10px;
    margin-bottom: 0;
  }

  .reminder-item {
    width: 200px;
    padding: 0 10px;
    margin-bottom: 0;
  }
}
</style>